use env_logger::Builder;
use std::time::Duration;
mod vegas_strategy;
use chrono::{Datelike, Duration as ChronoDuration, Local, NaiveDate, Timelike};
use serde::{Deserialize, Serialize};
use tokio;
use tokio::time::sleep;

mod config;
mod r#struct;

// 主策略逻辑
#[tokio::main]
async fn main() {
    // 初始化 环境变量
    Builder::from_default_env()
        .filter(None, log::LevelFilter::Info)
        .init();
    // 策略执行开始-结束时间
    let start_date = NaiveDate::from_ymd_opt(2018, 1, 1).unwrap();
    let end_date = NaiveDate::from_ymd_opt(2030, 11, 1).unwrap();
    let symbol = "BTCUSDT";
    // 创建策略实例
    let strategy = match vegas_strategy::VegasTunnelStrategy::new(symbol, start_date, end_date) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("创建策略实例失败: {:?}", e);
            return;
        }
    };
    println!("策略启动，将每隔一小时执行一次");

    // 获取当前时间，并计算到下一个整点的等待时间
    let now = Local::now();
    let next_hour = now
        .date_naive()
        .and_hms_opt(now.hour(), 0, 1)
        .unwrap()
        .and_local_timezone(Local)
        .unwrap();
    let mut next_execution = if now >= next_hour {
        next_hour + ChronoDuration::hours(1)
    } else {
        next_hour
    };
    loop {
        println!(
            "下次执行时间: {}",
            next_execution.format("%Y-%m-%d %H:%M:%S")
        );
        // 计算需要等待的时间
        let now = Local::now();
        let wait_duration = next_execution - now;
        if wait_duration.num_seconds() >= 0 {
            println!("等待 {} 秒后执行", wait_duration.num_seconds());
            sleep(Duration::from_secs(wait_duration.num_seconds() as u64)).await;
        }
        //执行策略
        println!("开始执行策略...");
        match strategy.run().await {
            Ok(_) => println!("策略执行成功"),
            Err(e) => eprintln!("策略执行出错: {:?}", e),
        }
        // 设置下一次执行时间为下一个整点
        next_execution = next_execution + ChronoDuration::hours(1);
    }
}
